﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using HandyControl.Controls;
using HandyControl.Data;
using Newtonsoft.Json;
using OfficeOpenXml;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using YJTMedicalAideManage.Cores;
using YJTMedicalAideManage.Cores.ApiModel;
using YJTMedicalAideManage.Cores.Attributes;
using YJTMedicalAideManage.Cores.Events;
using YJTMedicalAideManage.Cores.Globals;
using YJTMedicalAideManage.Cores.Helper;
using YJTMedicalAideManage.Cores.PusApiModel;
using YJTMedicalAideManage.Cores.Servers;
using YJTMedicalAideManage.MAM.Controls;
using YJTMedicalAideManage.MAM.Model;
using YJTMedicalAideManage.MAM.Services;

namespace YJTMedicalAideManage.MAM.ViewModels
{
    public class MAMViewModel : InheritBase
    {
        #region 内部字段
        private MAMDto _originalData;
        private readonly IDialogService _dialogService;
        private int PageSize = 12;//默认显示12条数据
        private readonly ApiService _apiService;
        private List<MAMDto> mAMDtos = new List<MAMDto>();
        #endregion

        #region ctor
        public MAMViewModel(IDialogService dialogService)
        {
            _dialogService = dialogService;
            _apiService = new ApiService();
            CopyCellContentCommand = new DelegateCommand<object>(ExecuteCopyCellContent);
            AddCommand = new DelegateCommand(() => { OpenEditDialog(true); });
            EditCommand = new DelegateCommand<MAMDto>(s => { OpenEditDialog(false, s); });
            QueryCommand = new DelegateCommand(async () => { await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await Query()); });
            ExcelCommand = new DelegateCommand(Excel);
            Init();
        }
        #endregion

        #region 命令

        #endregion
        public DelegateCommand<object> CopyCellContentCommand { get; private set; }

        public DelegateCommand QueryCommand { get; private set; }
        /// <summary>
        /// 添加
        /// </summary>
        public DelegateCommand AddCommand { get; private set; }
        /// <summary>
        /// 导出
        /// </summary>
        public DelegateCommand ExcelCommand { get; private set; }
        /// <summary>
        /// 编辑
        /// </summary>
        public DelegateCommand<MAMDto> EditCommand { get; private set; }

        #region 属性
        private int totalQuantity;
        public int TotalQuantity
        { 
            get => totalQuantity;
            set
            {
                totalQuantity = value;
                RaisePropertyChanged();
            }
        }
        public MAMDto OriginalData
        {
            get => _originalData;
            set
            {
                _originalData = value;
                RaisePropertyChanged();
            }
        }
        private MAMDto m_originalData;
        public MAMDto M_OriginalData
        {
            get => m_originalData;
            set
            {
                m_originalData = value;
                RaisePropertyChanged();
            }
        }
        private int maxPageCount;
        /// <summary>
        /// 最大页码
        /// </summary>
        public int MaxPageCount
        {
            get => maxPageCount;
            set
            {
                maxPageCount = value;
                RaisePropertyChanged();
            }
        }
        private int currentPage = 1;
        /// <summary>
        /// 最大页码
        /// </summary>
        public int CurrentPage
        {
            get => currentPage;
            set
            {
                currentPage = value;
                RaisePropertyChanged();
            }
        }
        #endregion

        #region 集合
        private ObservableCollection<MAMDto> mams = new ObservableCollection<MAMDto>();

        public ObservableCollection<MAMDto> MAMs
        {
            get => mams;
            set
            {
                mams = value;
                RaisePropertyChanged();
            }
        }
        #endregion
        #region 方法
        private void ExecuteCopyCellContent(object parameter)
        {
            if (parameter == null) return;
            if (parameter is string content)
            {
                if (content.Length > 20)
                {
                    foreach (var item in MAMs)
                    {
                        item.Visibility = Visibility.Visible;
                        item.Tooltip = content;
                    }
                }
                else
                {
                    foreach (var item in MAMs)
                    {
                        item.Visibility = Visibility.Collapsed;
                    }
                }
            }
            else
            {
                
            }
        }

        private void SwitchItem(string info) => Growl.Info(info);
        private void Init()
        {
            OriginalData = new MAMDto();
            M_OriginalData = new MAMDto();
            M_OriginalData.StatusList.Add("全部");
            M_OriginalData.StatusList.Add("启用");
            M_OriginalData.StatusList.Add("停用");
            PaginationEvent.Instance.Subscribe(PageUpdate);
            StatusEvent.Instance.Subscribe(Status);
            QueryCommand.Execute();
        }
        private async void Status(string id)
        {
            var data = await _apiService.StateAsync(id);
            if (data.status != "success")
            {
                MessgaeError($"{data.msg}");
                return;
            }
            await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await Query());

            MessgaeSuccess("状态变更成功！");
        }
        private void PageUpdate()
        {
            var pagedData = mAMDtos.Skip((CurrentPage - 1) * PageSize).Take(PageSize).ToList();
            MAMs.Clear();
            foreach (var item in pagedData)
            {
                MAMs.Add(item);
            }
        }
        private void Excel()
        {
            string[] dclheaders = new string[] { "姓名", "账号", "联系电话", "地址", "添加时间", "状态" };
            List<string[]> dzdata = new List<string[]>(); // 预分配内存
            foreach (var item in mAMDtos.ToArray())
            {
                string[] itemData = new string[] { item.Name, item.Username, item.Tel, item.Address, item.CreateTime, (item.Status == "0" ? "启用" : "停用") };
                dzdata.Add(itemData);
            }
            ExcelHelper.Instance.WriteDataToNewExcel(dclheaders, dzdata, DateTime.Now.ToString("yyyyyyyy-MM-dd-HH-m-ss"));
        }
        [ShowLoadingMask]
        private async Task Query()
        {
            MAMs = new ObservableCollection<MAMDto>();
            mAMDtos = new List<MAMDto>();
            if (M_OriginalData != null)
            {
                M_OriginalData.page = "1";
                M_OriginalData.limit = "9999999999";
                var data = await _apiService.AssInitAsync(M_OriginalData.MAMDtoToassinit());
                if (data != null)
                {
                    if (data.status == "success")
                    {
                        foreach (var item in data.data)
                        {
                            mAMDtos.Add(M_OriginalData.MapAssToMAMDto(item));
                        }
                        mAMDtos = mAMDtos.OrderByDescending(s => Convert.ToDateTime(s.CreateTime)).ToList();
                        MaxPageCount = (int)Math.Ceiling((double)mAMDtos.Count / PageSize);
                        TotalQuantity = mAMDtos.Count;
                    }
                    else
                    {
                        MessgaeError(data.msg);
                        if (data.msg.Contains("登录认证失败"))
                        {
                            var data1 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                            CloseStringEvent.Instance.PushMessage("");
                            return;
                        }
                        return;
                    }
                }
                

            }
            PageUpdate();
        }
        private async void OpenEditDialog(bool isbool, MAMDto dto = null)
        {
            MAMDto mAMDto = new MAMDto();
            if (!isbool)
            {
                var data = await _apiService.AssEditInitAsync(dto.OperatorId);
                mAMDto = dto.MapAssToMAMDto(data.data);
                dto.Live_address = mAMDto.Live_address;
                dto.Pwd = mAMDto.Pwd;
            }
            var parameters = new DialogParameters
           {
               { "IsEnableds", isbool },  // 传递的数据
               { "EditedData", dto },  // 传递的数据
               
           };

            _dialogService.ShowDialog(nameof(AddOrEditPagesDialog), parameters, async r =>
            {
                if (r.Result == ButtonResult.OK)
                {
                    var EditedData = r.Parameters.GetValue<AssAddDto>("EditedData");

                    if (EditedData != null)
                    {
                        EditedData.TenantId = GlobalApp.Instance.ClinicId;
                        EditedData.RoleId = GlobalApp.Instance.Role_Id;
                        EditedData.Scale = GlobalApp.Instance.Scale;
                        if (!isbool)
                        {
                            var rulest = await _apiService.AssEditAsync(EditedData.MapAssAddDtoToAssistantadd(EditedData));
                            if (rulest.status == "success")
                            {
                                MessgaeSuccess("保存成功！");
                            }
                            else
                            {
                                MessgaeError($"{rulest.msg}");
                                if (rulest.msg.Contains("登录认证失败"))
                                {
                                    var data1 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                                    CloseStringEvent.Instance.PushMessage("");
                                    return;
                                }
                                return;
                            }
                        }
                        else
                        {
                            var rulest = await _apiService.AssAddAsync(EditedData.MapAssAddDtoToAssistantadd(EditedData));

                            if (rulest.status == "success")
                            {
                               var data = await _apiService.RelationDocAsync(rulest.data.doctor_id.ToString());
                                if (data.status != "success")
                                {
                                    MessgaeError($"{data.msg}");
                                    if (rulest.msg.Contains("登录认证失败"))
                                    {
                                        var data2 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                                        CloseStringEvent.Instance.PushMessage("");
                                        return;
                                    }
                                    return;
                                }
                                var data1= await _apiService.TenantArrAsync(rulest.data.doctor_id.ToString());
                                if (data1.status != "success")
                                {
                                    MessgaeError($"{data1.msg}");
                                    if (rulest.msg.Contains("登录认证失败"))
                                    {
                                        var data3 = await _apiService.logoutAsync(GlobalApp.Instance.Manager_Id);
                                        CloseStringEvent.Instance.PushMessage("");
                                        return;
                                    }
                                    return;
                                }
                                MessgaeSuccess("保存成功！");
                            }
                            else
                            {
                                MessgaeError(rulest.msg);
                                if (rulest.msg.Contains("登录认证失败"))
                                {
                                    CloseStringEvent.Instance.PushMessage("");
                                    return;
                                }
                                return;
                            }
                        }
                    }
                }
                await LoadingMaskInterceptor.Instance().InterceptAsync(async () => await Query());
            });
        }
        #endregion
    }
    public class HoverInfo
    {
        public object HoveredElement { get; set; }
        public object ObjectInfo { get; set; }
    }
}
